﻿
Namespace Base
    ''' <summary>
    ''' Connection will be use to provide a connection to the database and provide Command Object from that connection 
    ''' </summary>
    ''' <remarks></remarks>
    Public NotInheritable Class Connection
        Private Shared WithEvents _db As SqlConnection
        Public Shared InfoMessage As String
        Public Shared ReadOnly Property Db() As SqlConnection
            Get
                'Dim swatch As Stopwatch = New Stopwatch()
                'swatch.Start()
                Dim tryAgain As Integer = 0
                _db = New SqlConnection()
                _db.ConnectionString = AppManager.ConnectionString
                _db.Open()
                'swatch.Stop()
                'Console.WriteLine("OpenDB: " + swatch.Elapsed.ToString)
                While _db.State = ConnectionState.Connecting AndAlso tryAgain <= 1000
                    tryAgain += 1
                    'pour quand la connection est très slow...
                End While
                Return _db
            End Get
        End Property

        Public Shared Sub CloseConnection()
            AppManager.IsConnected = False
            AppManager.ConnectionString = String.Empty
            If _db IsNot Nothing AndAlso _db.State = ConnectionState.Open Then
                _db.Close()
            End If
            If _db IsNot Nothing Then
                SqlConnection.ClearAllPools()
            End If
        End Sub

        Public Shared Function Command() As SqlCommand
            Dim cmd As SqlCommand = Db.CreateCommand()
            cmd.CommandTimeout = 0 'no limits...
            Return cmd
        End Function

        Private Shared Sub _db_InfoMessage(sender As Object, e As System.Data.SqlClient.SqlInfoMessageEventArgs) Handles _db.InfoMessage
            Dim err As SqlError
            Dim sb As Text.StringBuilder = New Text.StringBuilder()
            For Each err In e.Errors
                sb.AppendLine(err.Message)
            Next
            If e.Errors.Count > 0 Then
                'outstandingissue: Elle ne leve pas si executer au runtime...aleblanc
                'MyApplication_UnhandledException du ApplicationEvents.vb devrait l'attraper...
                'Throw New Exception(sb.ToString)
            End If
        End Sub
    End Class
End Namespace


